package com.wyzz.hr.io.extend;

import java.lang.reflect.Method;
import java.util.*;

import com.wyzz.hr.bo.IEmpshiftBo;
import com.wyzz.hr.bo.impl.ExaminDateUtil;
import com.wyzz.hr.hibernate.IHibernateUtil;
import com.wyzz.hr.pojo.Attendshift;
import com.wyzz.hr.pojo.Employee;
import com.wyzz.hr.pojo.Empshift;
import com.wyzz.hr.pojo.ExaminShiftBean;
import com.wyzz.hr.spring.SpringBeanFactory;
import com.wyzz.hr.util.DatabaseSysConfigManager;
import com.wyzz.hr.util.DateUtil;

public class IExaminShift extends ICheckAndInsert {
	private class ObjAndRow {

		public Integer rowNum;
		public ExaminShiftBean bean;

		ObjAndRow(Integer rowNum, ExaminShiftBean bean) {
			this.rowNum = rowNum;
			this.bean = bean;
		}
	}

	public IExaminShift() {
		msgNotExist = "\u7F16\u53F7\u4E3A{0}\u7684\u5458\u5DE5\u4E0D\u5B58\u5728\uFF01";
		msgShiftNotExist = "\u4EE3\u7801\u4E3A{0}\u7684\u73ED\u6B21\u672A\u542F\u7528\u6216\u4E0D\u5B58\u5728\uFF01";
		msgEmpNoShift = "\u7F16\u53F7\u4E3A{0}\u7684\u5458\u5DE5\u4E3A\u975E\u6392\u73ED\u4EBA\u5458\uFF0C\u4E0D\u80FD\u6392\u73ED\uFF01";
	}

	public int[] insertTransmit(List insertList, CommonParameters commonParas) {
		Employee currentEmp = commonParas.getCurrEmp();
		Map empInfoMap = getEmpInfo();
		Map shiftMap = getAllShift();
		int result[] = { 0, 0 };
		String yearMonth = commonParas.getImportParameter();
		Map sysMap = DatabaseSysConfigManager.getInstance().getProperties();
		String config = (String) sysMap.get("sys.examin.month.sum");
		Date dateArr[] = ExaminDateUtil.getDateArray(yearMonth, config);
		Date startDate = dateArr[0];
		Date endDate = dateArr[1];
		List excelDataList = insertList;
		int hasTitle = 1 - commonParas.getInmatchModel().getImmNoTitle()
				.intValue();
		Map objInsertMap = new HashMap();
		int rowNum = hasTitle + 1;
		ExaminShiftBean bean;
		for (Iterator i$ = excelDataList.iterator(); i$.hasNext(); objInsertMap
				.put(bean.getEmp().getEmpDistinctNo(), new ObjAndRow(Integer
						.valueOf(rowNum++), bean)))
			bean = (ExaminShiftBean) i$.next();

		String empIdArr[] = new String[excelDataList.size()];
		List empshiftList = new ArrayList();
		List deleteList = new ArrayList();
		List toCheckList = new ArrayList();
		List blankList = new ArrayList();
		Iterator iter = objInsertMap.entrySet().iterator();
		String empDistinctNo = null;
		ObjAndRow rowObj = null;
		ExaminShiftBean shiftBean = null;
		Employee currEmp = null;
		while (iter.hasNext()) {
			java.util.Map.Entry entry = (java.util.Map.Entry) iter.next();
			empDistinctNo = (String) entry.getKey();
			rowObj = (ObjAndRow) entry.getValue();
			rowNum = rowObj.rowNum.intValue();
			shiftBean = rowObj.bean;
			currEmp = (Employee) empInfoMap.get(empDistinctNo);
			if (currEmp == null)
				commonParas.addErrorMessage(msgNotExist, Integer
						.valueOf(rowNum), new String[] { empDistinctNo });
			else if (currEmp.getEmpShiftType().intValue() == 0) {
				commonParas.addErrorMessage(msgEmpNoShift, Integer
						.valueOf(rowNum), new String[] { empDistinctNo });
			} else {
				empIdArr[rowNum - hasTitle - 1] = currEmp.getId();
				Class beanClass = shiftBean.getClass();
				Method getMethod = null;
				Date tempDate = (Date) startDate.clone();
				String shiftStr = null;
				while (tempDate.compareTo(endDate) <= 0) {
					String dayStr = DateUtil.formatDate(tempDate).substring(8,
							10);
					dayStr = Integer.parseInt(dayStr) >= 10 ? dayStr : dayStr
							.substring(1);
					try {
						getMethod = beanClass.getMethod((new StringBuilder())
								.append("get_").append(dayStr).toString(),
								new Class[0]);
						shiftStr = (String) getMethod.invoke(shiftBean,
								new Object[0]);
					} catch (Exception e) {
						e.printStackTrace();
					}
					if (shiftStr == null) {
						blankList.add((new StringBuilder()).append(
								currEmp.getId()).append("").append(
								DateUtil.formatDate(tempDate)).toString());
						tempDate = DateUtil.dateAdd(tempDate, 1);
					} else if (shiftMap.get(shiftStr) == null) {
						commonParas.addErrorMessage(msgShiftNotExist, Integer
								.valueOf(rowNum), new String[] { shiftStr });
						tempDate = DateUtil.dateAdd(tempDate, 1);
					} else {
						Empshift empshift = new Empshift();
						empshift.setEmpshiftEmpNo((Employee) empInfoMap
								.get(empDistinctNo));
						empshift.setEmpshiftShiftNo((Attendshift) shiftMap
								.get(shiftStr));
						empshift.setEmpshiftDate(DateUtil.parseDateByFormat(
								DateUtil.formatDate(tempDate), "yyyy-MM-dd"));
						empshift.setEmpshiftCreateTime(new Date());
						empshift.setEmpshiftCreateBy(currentEmp.getId());
						empshift.setEmpshiftLastChangeTime(new Date());
						empshift.setEmpshiftLastChangeBy(currentEmp.getId());
						empshiftList.add(empshift);
						toCheckList.add(empshift);
						tempDate = DateUtil.dateAdd(tempDate, 1);
					}
				}
			}
		}
		if ("SUB".equals(commonParas.getAuthCondition()))
			chechDeptAuth(currentEmp, empIdArr, commonParas);
		String overrideConfig = (String) sysMap
				.get("sys.examin.shiftimport.override");
		IEmpshiftBo empshiftBo = (IEmpshiftBo) SpringBeanFactory
				.getBean("empshiftBO");
		Map empshiftMap = empshiftBo.getEmpshiftList(empIdArr, startDate,
				endDate);
		Iterator iter1 = empshiftList.iterator();
		Iterator checkIter = toCheckList.iterator();
		Empshift temp = null;
		Empshift existTemp = null;
		Empshift checkTemp = null;
		do {
			if (!iter1.hasNext() || !checkIter.hasNext())
				break;
			temp = (Empshift) iter1.next();
			checkTemp = (Empshift) checkIter.next();
			existTemp = (Empshift) empshiftMap.get((new StringBuilder())
					.append(temp.getEmpshiftEmpNo().getId()).append(
							DateUtil.formatDateToS(temp.getEmpshiftDate(),
									"yyyy-MM-dd")).toString());
			if (existTemp != null)
				if ("0".equals(overrideConfig)) {
					iter1.remove();
					checkIter.remove();
				} else {
					temp.setId(existTemp.getId());
					temp.setEmpshiftCreateBy(existTemp.getEmpshiftCreateBy());
					temp.setEmpshiftCreateTime(existTemp
							.getEmpshiftCreateTime());
				}
		} while (true);
		if ("1".equals(overrideConfig)) {
			Iterator i$ = blankList.iterator();
			do {
				if (!i$.hasNext())
					break;
				String key = (String) i$.next();
				temp = (Empshift) empshiftMap.get(key);
				if (temp != null) {
					deleteList.add(temp);
					try {
						checkTemp = (Empshift) temp.clone();
					} catch (CloneNotSupportedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					checkTemp.setEmpshiftShiftNo(null);
					toCheckList.add(checkTemp);
				}
			} while (true);
		}
		List errorList = empshiftBo.validateShift(toCheckList, empshiftMap);
		empshiftBo.checkShiftSchedule(errorList, empIdArr, empshiftList);
		String error;
		for (Iterator i$ = errorList.iterator(); i$.hasNext(); commonParas
				.addErrorMessage(error, null, new String[0]))
			error = (String) i$.next();

		if (!commonParas.getIoMessages().hasErrorMsg()) {
			empshiftBo.batchSaveEmpshift(empshiftList, deleteList);
			result[0] = excelDataList.size();
		}
		return result;
	}

	private Map getEmpInfo() {
		IHibernateUtil dao = (IHibernateUtil) SpringBeanFactory.getBean("dao");
		String hql = "select empDistinctNo, id, empShiftType from Employee";
		List empList = dao.exeHqlList(hql);
		Object info[] = null;
		Map empMap = new HashMap();
		for (int i = 0; i < empList.size(); i++) {
			info = (Object[]) (Object[]) empList.get(i);
			Employee emp = new Employee((String) info[1]);
			emp.setEmpShiftType((Integer) info[2]);
			empMap.put((String) info[0], emp);
		}

		return empMap;
	}

	private Map getAllShift() {
		IHibernateUtil dao = (IHibernateUtil) SpringBeanFactory.getBean("dao");
		String hql = "from Attendshift";
		List shiftList = dao.exeHqlList(hql);
		Attendshift shift = null;
		Map shiftMap = new HashMap();
		for (int i = 0; i < shiftList.size(); i++) {
			shift = (Attendshift) shiftList.get(i);
			shiftMap.put(shift.getAttsShortName(), shift);
		}

		return shiftMap;
	}

	String msgNotExist;
	String msgShiftNotExist;
	String msgEmpNoShift;
}
